package mongo

import (
	"context"
	"core/corestruct"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

/*
mongo分页，只能id 倒序
https://blog.csdn.net/m0_56137272/article/details/132629538
*/
type PageService[T any] struct {
	ColName  string
	Filer    bson.M
	PageNo   int
	PageSize int
}

func (p *PageService[T]) Page() (*corestruct.Page[T], error) {
	var c, err = p.count()
	if err != nil {
		return nil, err
	}
	var r = &corestruct.Page[T]{}
	r.TotalRow = c
	r.PageNumber = p.PageNo
	r.PageSize = p.PageSize
	r.Records = make([]T, 0)

	var skip = int64((r.PageNumber - 1) * r.PageSize)

	var take = r.PageSize
	take -= len(r.Records)

	data, err := p.list(skip, int64(take))
	if err != nil {
		return nil, err
	}
	r.Records = data

	return r, nil
}
func (p *PageService[T]) count() (int64, error) {
	var col = Db.Collection(p.ColName)
	var c, err = col.CountDocuments(context.Background(), p.Filer)
	return c, err
}
func (p *PageService[T]) list(skip int64, take int64) ([]T, error) {
	var r = make([]T, 0)
	var col = Db.Collection(p.ColName)

	opts := options.Find().SetSort(bson.D{{"_id", -1}}).
		SetSkip(skip).
		SetLimit(take)

	var cur, err = col.Find(context.Background(), p.Filer, opts)
	if err != nil {
		log.Fatal(err)
	}
	defer cur.Close(context.Background())
	for cur.Next(context.Background()) {
		var m T
		err := cur.Decode(&m)
		if err != nil {
			return nil, err
		}
		r = append(r, m)
	}

	return r, nil
}
